package com.kly.cashmall.base.app_action;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;

import com.kly.cashmall.AppApplication;
import com.kly.cashmall.module.mine.AboutUsActivity;
import com.kly.cashmall.module.mine.MessageActivity;
import com.kly.cashmall.module.home.HomePageActivity;
import com.kly.cashmall.module.home.home_tab.tab_view.MenuTabInfo;
import com.kly.cashmall.module.login.LoginActivity;
import com.kly.cashmall.module.login.presenter.LoginPresenter;
import com.kly.cashmall.module.order.LoanDetailsActivity;
import com.kly.cashmall.module.order.LoanRepayDetailsActivity;
import com.kly.cashmall.module.products.ProductDetailActivity;
import com.kly.cashmall.module.products.ProductDetailConfirmActivity;
import com.kly.cashmall.module.products.LoanSuccessActivity;
import com.kly.cashmall.module.profile.GeneralInfoActivity;
import com.kly.cashmall.module.profile.ProfileActivity;
import com.kly.cashmall.module.repay.RepayResultActivity;
import com.kly.cashmall.module.web.WebViewActivity;
import com.kly.cashmall.popup.LogoutPopupWindow;
import com.kly.cashmall.services.UserInfoHelper;
import com.kly.cashmall.utils.function.BundleHelper;
import com.kly.cashmall.utils.data.TextUtil;

/**
 * @author
 * @date 2017/8/30
 */
public class BaseActionHelper {

    private Context context;
    private LogoutPopupWindow popup;

    private BaseActionHelper(Context context) {
        this.context = context;
    }

    public static BaseActionHelper with(Context context) {
        return new BaseActionHelper(context);
    }

    public Context getContext() {
        return context == null ? AppApplication.getInstance() : context;
    }

    private boolean doNeedLogin(String action) {
        if (!UserInfoHelper.getInstance().isLogin()) {
            context.startActivity(LoginActivity.callRedirectOtherActionIntent(getContext(), LoginPresenter.LINK_URL,
                                    BundleHelper.create().putString(LoginPresenter.LINK_URL, action).get()));
            return true;
        }
        return false;
    }

    public boolean handleAction(String action) {
        return handleAction(action, false);
    }

    public boolean handleAction(String action, boolean needLogin) {
        if (TextUtils.isEmpty(action)) {
            return false;
        }
        //如果需要登录，但是没有登录，就先跳转登录
        if (needLogin && doNeedLogin(action)) {
            return false;
        }
        if (ActionEnums.URLJS.isMatch(action)) {
            String url = action.substring(ActionHeads.URLJS.length());
            doActionURL(url);
            return true;
        }
        if (ActionEnums.URLNONJS.isMatch(action)) {
            String url = action.substring(ActionHeads.URLNONJS.length());
            doActionURL(url);
            return true;
        }
        if (action.startsWith("http://") || action.startsWith("https://")) {
            doActionURL(action);
            return true;
        }
        if (ActionEnums.URLExternal.isMatch(action)) {
            String url = action.substring(ActionHeads.URLExternal.length());
            doActionExternalURL(url);
            return true;
        }

        if (ActionEnums.LMActionProfile.isMatch(action)) {
            doActionProfileData(action);
            return true;
        }

        if (ActionEnums.LMActionProductConfirm.isMatch(action)) {
            doActionProductDeatilSure(action);
            return true;
        }
        if (ActionEnums.LMActionLogin.isMatch(action)) {
            doNeedLogin(action);
            return true;
        }
        if (ActionEnums.LMActionProductList.isMatch(action)) {
            doProductAction();
            return true;
        }
        if (ActionEnums.LMActionHome.isMatch(action)) {
            doHomeAction();
            return true;
        }
        if (ActionEnums.LMActionOrderList.isMatch(action)) {
            doOrderAction(action);
            return true;
        }
        if (ActionEnums.LMActionOrderDetail.isMatch(action)) {
            doOrderDetails(action);
            return true;
        }
        if (ActionEnums.LMActionMine.isMatch(action)) {
            doPersonAction();
            return true;
        }
        if (ActionEnums.LMActionProductDetail.isMatch(action)) {
            doActionProductDeatil(action);
            return true;
        }
        if (ActionEnums.LMActionPersonalInfo.isMatch(action) || ActionEnums.LMActionPersonalAadhaar.isMatch(action)) {
            doActionPersonalInfo(action);
            return true;
        }
        if (ActionEnums.LMActionProductConfirmSuccess.isMatch(action)) {
            doActionProductSuccess(action);
            return true;
        }

        if (ActionEnums.TEL.isMatch(action)) {
            callPhone(action);
            return true;
        }

        if (ActionEnums.LMActionLogout.isMatch(action)) {
            doActionLogout();
            return true;
        }
        if (ActionEnums.LMActionRepayDetails.isMatch(action)) {
            doRepayDetails(action);
            return true;
        }
        if (ActionEnums.LMActionNotice.isMatch(action)) {
            doActionNotice();
            return true;
        }
        if (ActionEnums.LMActionFinish.isMatch(action)) {
            doFinishActivity();
            return true;
        }

        if (ActionEnums.LMActionMobileLogin.isMatch(action)) {
            doActionMobileLogin(action);
            return true;
        }
        if (ActionEnums.LMActionJumpGoogle.isMatch(action)) {
            doDownLoadGoogle(action);
            return true;
        }
        if (ActionEnums.LMActionRepayResult.isMatch(action)) {
            doRepayResult(action);
            return true;
        }
        if (ActionEnums.LMActionAboutUs.isMatch(action)) {
            doActionAboutUs();
            return true;
        }
        return false;
    }

    private void doActionMobileLogin(String action) {
        String type = ActionParams.parse(action).get("type", "");
        if (TextUtil.isEmpty(type)) {
            type = "-1";
        }
        context.startActivity(LoginActivity.callIntent(getContext(), Integer.parseInt(type)));
    }

    private void doActionAboutUs() {
        context.startActivity(AboutUsActivity.newIntent(context));
    }

    /**
     * 退出activity
     */
    private void doFinishActivity() {
        if (getContext() instanceof Activity) {
            ((Activity) getContext()).finish();
        }
    }

    private void doActionNotice() {
        context.startActivity(MessageActivity.newIntent(context));
    }

    private void doActionLogout() {
        popup = new LogoutPopupWindow(getContext(), new LogoutPopupWindow.Callback() {
            @Override
            public void onClickListener() {
                popup.dismiss();
                UserInfoHelper.getInstance().setToken("");
                //退出登陆
                ((Activity) getContext()).finish();
                context.startActivity(LoginActivity.callIntent(getContext()));
            }
        });
        popup.setPopupGravity(Gravity.CENTER);
        popup.showPopupWindow();
    }

    /**
     * 订单详情
     */
    private void doOrderDetails(String action) {
        String tradeNo = ActionParams.parse(action).get("tradeNo", "");
        context.startActivity(LoanDetailsActivity.newIntent(context, tradeNo));
    }

    private void doRepayDetails(String action) {
        String tradeNo = ActionParams.parse(action).get("billNo", "");
        context.startActivity(LoanRepayDetailsActivity.newIntent(context, tradeNo));
    }

    private void doRepayResult(String action) {
        String billNo = ActionParams.parse(action).get("billNo", "");
        String type = ActionParams.parse(action).get("type", "");
        context.startActivity(RepayResultActivity.callIntent(context,billNo, Integer.parseInt(type)));
    }

    /**
     * 进入我的页面
     */
    private void doPersonAction() {
        context.startActivity(HomePageActivity.newIntent(getContext(), MenuTabInfo.TAG_MINE_CENTER, null));
    }

    /**
     * 进入产品列表页面
     */
    private void doProductAction() {
        context.startActivity(HomePageActivity.newIntent(getContext(), MenuTabInfo.TAG_LOAN_PRODUCTS, null));
    }

    /**
     * 进入首页页面
     */
    private void doHomeAction() {
        context.startActivity(HomePageActivity.newIntent(getContext(), MenuTabInfo.TAG_HOME, null));
    }

    /**
     * 进入订单列表页面
     */
    private void doOrderAction(String action) {
        String type = ActionParams.parse(action).get("type", "");
        Bundle bundle = null;
        if (!TextUtil.isEmpty(type)) {
            bundle = new Bundle();
            bundle.putInt("type", Integer.parseInt(type));
        }
        context.startActivity(HomePageActivity.newIntent(getContext(), MenuTabInfo.TAG_LOAN_ORDERS, bundle));
    }

    private void doActionProductDeatil(String action) {
        String categoryCode = ActionParams.parse(action).get("categoryCode", "");
        String merchantCode = ActionParams.parse(action).get("merchantCode", "");
        if (!TextUtil.isEmpty(categoryCode)) {
            context.startActivity(
                    ProductDetailActivity.newIntent(getContext(), categoryCode,merchantCode));
        }
    }

    private void doActionProductDeatilSure(String action) {
        String productCode = ActionParams.parse(action).get("productCode", "");
        String merchantCode = ActionParams.parse(action).get("merchantCode", "");
        if (!TextUtil.isEmpty(productCode)) {
            context.startActivity(
                    ProductDetailConfirmActivity.newIntent(getContext(), productCode,merchantCode));
        }
    }


    private void doActionProfileData(String action) {
        String source = ActionParams.parse(action).get("source", "");
        context.startActivity(ProfileActivity.newIntent(context, source));
    }

    private void doActionPersonalInfo(String action) {
        String type = ActionParams.parse(action).get("type", "");
        String title = ActionParams.parse(action).get("title", "");
        context.startActivity(GeneralInfoActivity.callIntent(getContext(), type, title));
    }

    private void doActionProductSuccess(String action) {
        String title = ActionParams.parse(action).get("title", "");
        String msg = ActionParams.parse(action).get("msg", "");
        context.startActivity(LoanSuccessActivity.newIntent(getContext(),title,msg));
    }

    private void doActionURL(String url) {
        String type = ActionParams.parse(url).get("type", "");
        String billNo = ActionParams.parse(url).get("billNo", "");

        boolean data;
        while (!TextUtils.isEmpty(url) && url.startsWith("/")) {
            url = url.substring(1);
        }
        if (url.contains("<from>")) {
            data = true;
        } else {
            data = false;
        }
        if (!TextUtil.isEmpty(type)) {
            context.startActivity(WebViewActivity.callIntent(getContext(), "", url, data, type, billNo));
        } else {
            context.startActivity(WebViewActivity.callIntent(getContext(), "", url, data));
        }
    }

    private void callPhone(String action) {
        String mobile = ActionParams.parse(action).get("tel", "");
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + mobile));
            getContext().startActivity(intent);
    }


    private void doActionExternalURL(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        context.startActivity(intent);
    }

    private void doDownLoadGoogle(String action) {
        String url = ActionParams.parse(action).get("url", "");

        final String GOOGLE_PLAY = "com.android.vending";
        try {
            if (TextUtils.isEmpty(context.getPackageName())) {
                return;
            }
            Uri uri = Uri.parse("market://details?id=" + url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage(GOOGLE_PLAY);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
